<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>工单维护</title>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" type="text/css" href="${prefix}/stylesheets/theme.css">
<link rel="stylesheet" type="text/css" href="${prefix}/stylesheets/reveal.css">
<link rel="stylesheet" type="text/css" href="${prefix}/lib/font-awesome/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="${prefix}/lib/bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="${prefix}/lib/jqueryui/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="${prefix}/lib/jqueryui/jquery-ui.structure.css">
<link rel="stylesheet" type="text/css" href="${prefix}/lib/jqueryui/jquery-ui.theme.css">

<script src="${prefix}/lib/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="${prefix}/lib/ajaxfileupload.js" type="text/javascript"></script>
<script src="${prefix}/lib/jquery-form.js" type="text/javascript"></script>
<script src="${prefix}/lib/jquery.reveal.js" type="text/javascript"></script>
<script src="${prefix}/lib/jqueryui/jquery-ui.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function(){
	$("#fenpeiType").change(function() {
		//如果条件成立，说明是抢单模式；否则是指派模式
		if($("#fenpeiType").val() == "1") {
			$("#qiangdanModuleDiv").css("display" , "");
			$("#zhipaiModuleDiv").css("display" , "none");
			
			//根据不同的单据，决定人员工号确定后，哪个控件获取焦点
			if(orderCode == "0001") {
				$("#commoditySelectText").focus();
			} else {
				$("#remark").focus();
			}
		} else {
			$("#qiangdanModuleDiv").css("display" , "none");
			$("#zhipaiModuleDiv").css("display" , "");
			//人员输入框获得焦点
			$("#zhipaiModule_userCode").focus();
		}
	});
	
	//当指派模式的时候，员工工号输入框输入了信息并且回车，查询工号对应的用户名
	$("#zhipaiModule_userCode").keyup(function(e) {
		var userCode = $.trim($("#zhipaiModule_userCode").val());
		if(e.keyCode == 13) {
			if(userCode == "") {
				alert("请输入员工工号。");
				return;
			}
			
			var storeid = "${admin.storefront.uid}";
			$.ajax({
                url: "${prefix}/storeuser/queryStoreuserByWorknumber?storeid=" + storeid + "&workNumber=" + userCode,
                async: false,
                dataType: "json",
                success: function(data) {
                	//错误信息
        			if(data.responsecode != "E200") {
        				alert(data.errorinfo);
        				return;
        			}
                	
                	var user = data.data;
                	//如果条件成立，则查无此人
                	if(user == null) {
                		$("#zhipaiModule_userid").val("");
                		$("#zhipaiModule_userName_view").html("");
                		alert("查无此人，请检查输入的工号！");
                		$("#zhipaiModule_userCode").focus();
        				return;
                	} else {
                		$("#zhipaiModule_userid").val(user.uid);
                		$("#zhipaiModule_userName_view").html(user.userName);
                	}
                	
                	//根据不同的单据，决定人员工号确定后，哪个控件获取焦点
					if(orderCode == "0001") {
						$("#commoditySelectText").focus();
					} else {
						$("#remark").focus();
					}
                }
            });
		}
	});
	
	//页面加载完成后，控制光标在“房间号输入位置”，设置回车效果
	$("#roomNo").focus();
	$("#roomNo").keyup(function(e) {
		if(e.keyCode == 13) {
			$("#orderType").focus();
		}
	});
	
	//当输入完成工单类型编号，并且回车的时候
	$("#orderType").keyup(function(e) {
		if(e.keyCode == 13) {
			orderCode = $.trim($("#orderType").val());
			companyid = "${admin.company.uid}";
			if(orderCode == "") {
				alert("请输入订单类型编号");
				return;
			}
			
			//查询工单基本信息
			$.ajax({
				type: "post",
				async: false,
				url: "${prefix}/ordertype/queryOrderTypeByCode?companyid=" + companyid + "&orderCode=" + orderCode,
				success: function(data) {
					//隐藏各div信息，免得出现异常数据
					$("#ordertypeDetails").css("display","none");
					$("#qiangdanModuleDiv").css("display","none");
					$("#commodityDetailsDiv").css("display","none");
					$("#remarkDetailsDiv").css("display","none");
					$("#zhipaiModuleDiv").css("display","none");
					
					var jsonData = eval('(' + data + ')');
					//错误信息
					if(jsonData.responsecode != "E200") {
						alert(jsonData.errorinfo);
						return;
					}
					
					//如果没有查找到这个编码，则要报错
					var orderType = jsonData.data;
					if(orderType == null || orderType == "") {
						alert("没有查找到对应的工单编码，请检查！");
						return;
					}
					
					//设置可见性
					$("#ordertypeDetails").css("display","");
					//根据当前可能已经选定的分配方式，决定qiangdanModuleDiv和zhipaiModuleDiv的可见性
					if($("#fenpeiType").val() == "1") {
						$("#qiangdanModuleDiv").css("display" , "");
						$("#zhipaiModuleDiv").css("display" , "none");
					} else {
						$("#qiangdanModuleDiv").css("display" , "none");
						$("#zhipaiModuleDiv").css("display" , "");
					}
					if(orderCode == "0001") {
						$("#commodityDetailsDiv").css("display","");
						$("#remarkDetailsDiv").css("display","none");
					} else {
						$("#commodityDetailsDiv").css("display","none");
						$("#remarkDetailsDiv").css("display","");
					}
					
					//初始化工单类型下的工单基本信息
					$("#orderTypeName").html(orderType.orderTypeName);
					$("#duration").val(orderType.duration);
					$("#integral").val(orderType.integral);
					
					//如果是消费单，那么显示商品信息的填写表格，并初始化下拉查询空间；
					//否则显示“任务说明”信息即可
					if(orderCode == "0001") {
						$("#commoditySelectText").focus();
					} else {
						$("#remark").focus();
					}
					
					//===========分配到
					$("input[name='fenpei']").attr("checked",false);
					var allFenpeis = $("input[name='fenpei']");
					var selectedFenpeis = orderType.userGroups;
					for(var index = 0 ; selectedFenpeis != null && index < selectedFenpeis.length ; index++) {
						var selectedFenpei = selectedFenpeis[index];
						var selected = false;
						
						for(var sum = 0 ; allFenpeis != null && sum < allFenpeis.length ; sum++) {
							var allFenpei = allFenpeis[sum];
							//如果条件成立，则表示需要选中
							if($(allFenpei).val() == selectedFenpei.uid) {
								$(allFenpei).attr("checked",true);
								break;
							}
						}
					}
				}
			});
		}
	});
	
	//与设定商品下拉选择框
	$("#commoditySelectText").autocomplete({
		source: function( request, response ){
			var commodityLikeName = $("#commoditySelectText").val();
			$.ajax({
                url: "${prefix}/commodity/queryCommodityLikeName",
                async: false,
                dataType: "json",
                data:{
                	likeName: encodeURI($.trim(request.term))
                },
                success: function( data ) {
                	var commoditys = data.data;
                	if(commoditys == null || commoditys.length == 0) {
                		return null;
                	}
                	
                	response($.map(commoditys, function(item) {
                        return {
							uid:item.uid,
							commodityName:item.commodityName,
							commodityCode:item.commodityCode,
							sortName:item.sortName,
							value: (item.commodityName + "【"+ item.sortName +"】")
                        }
                    }));
                }
            });
		},
		minLength: 1,
		//当选中时
		select: function( event, ui ) {
			$("#commoditySelectText_uid_hidden").val(ui.item.uid);
			$("#commoditySelectText_name_hidden").val(ui.item.commodityName);
			$("#commoditySelectText_sortname_hidden").val(ui.item.sortName);
		}
	});
	
	//当商品名称选定后，就跳转到输入数量的“输入框”
	$("#commoditySelectText").keyup(function(e) {
		if(e.keyCode == 13) {
			if($("#commoditySelectText_uid_hidden").val() == "") {
				alert("请在下拉框中选定一个商品");
				return;
			}
			
			//焦点跳到“数字输入”
			$("#commodityNumberText").val("")
			$("#commodityNumberText").focus();
		}
	});
	
	//当数量也进行了验证后，生成一行记录到“商品列表”上
	$("#commodityNumberText").keyup(function(e) {
		if(e.keyCode == 13) { 
			var pattern = /^[\d]{1,4}$/;
			var commodityNumber = $("#commodityNumberText").val();
			if(!pattern.test(commodityNumber)) {
				alert("请录入正确的商品数量（只能为数字，且最多4位）");
				return;
			}
			
			//===============开始将这个商品进行页面记录，增加已录入商品表的表格
			var html = "<tr id=\"selectedCommodity\" name=\"selectedCommodity\" commodityid=\"" + $("#commoditySelectText_uid_hidden").val() + "\" commodityNumber=\"" + $("#commodityNumberText").val() + "\">";
			html += "<td>";
			html += $("#commoditySelectText_name_hidden").val() + "【" + $("#commoditySelectText_sortname_hidden").val() + "】";
			html += "</td>";
			html += "<td>";
			html += $("#commodityNumberText").val();
			html += "</td>";
			html += "<td>";
			html += "<a href=\"javascript:void(0);\" onclick=\"removeCommodityDetail(this)\">删除</a>";
			html += "</td>";
			html += "</tr>";
			$("#commodityDetailsTbody").prepend(html);
			
			//===============清空目前的商品录入记录
			$("#commoditySelectText_uid_hidden").val("");
			$("#commoditySelectText_name_hidden").val("");
			$("#commoditySelectText_sortname_hidden").val("");
			$("#commoditySelectText").val("");
			$("#commodityNumberText").val("");
			
			//===============转到商品查询下拉框
			$("#commoditySelectText").focus();
		}
	});
});

//删除指定的“已选定工单”
function removeCommodityDetail(tdhref) {
	$(tdhref).parent().parent().remove();
} 

//添加工单的处理操作
function saveOrdertype() {
	//===============首先进行输入信息的赋值
	//房间信息
	var roomNo = $.trim($("#roomNo").val());
	//工单编号
	var orderTypeCode = $.trim($("#orderType").val());
	//工单耗时
	var duration = $.trim($("#duration").val());
	//工单积分
	var integral = $.trim($("#integral").val());
	//工单分配方式
	var fenpeiType = $("#fenpeiType").val();
	//分配模式下，选定的分配到的用户组
	var selectedFenpeis = $("input[name='fenpei'][checked]");
	//指派模式下，被指派用户的id
	var zhipaiUserid = $("#zhipaiModule_userid").val();
	//非“消费单”类型下的“任务说明信息”
	var remark = $.trim($("#remark").val());
	//“消费单”类型的，已经选型的商品tr
	var selectedCommodityTrs = $("tr[name='selectedCommodity']");
	
	//==========然后进行输入信息正误性的判断
	//判断填写的信息
	var goodForm = true;
	var error = "";
	if(roomNo == "") {
		goodForm = false
		error += "请输入可用的房间编号\n";
	}
	if(orderTypeCode == "") {
		goodForm = false
		error += "请输入可用的工单类型编号\n";
	}
	//标准耗时只能填写整数
	var pattern = /^[\d]+$/;
	if(!pattern.test(duration)) {
		goodForm = false
		error += "标准服务时间只能填写正整数\n";
	}
	if(!pattern.test(integral)) {
		goodForm = false
		error += "服务积分只能填写正整数\n";
	}
	//抢单模式下， 至少需要选择一个用户组
	if(fenpeiType == "1" && (selectedFenpeis == null || selectedFenpeis.length == 0)) {
		goodForm = false
		error += "抢单模式下，至少需要选择一个用户组\n";
	}
	if(fenpeiType == "2" && zhipaiUserid == "") {
		goodForm = false
		error += "指派模式下，需要输入被指派人员的员工工号\n";
	}
	
	//如果当前已输入的工单类型，不是消费服务单
	if(orderTypeCode != "0001" && orderTypeCode != "" && remark == "") {
		goodForm = false
		error += "请填写工单的任务说明\n";
	}
	if(orderTypeCode == "0001" && (selectedCommodityTrs == null || selectedCommodityTrs.length == 0)) {
		goodForm = false
		error += "请至少填写一条商品信息\n";
	}
	if(!goodForm) {
		alert(error);
		return;
	}
	
	//=====================然后开始组装提交的参数信息
	var storeid = "${admin.storefront.uid}";
	var data = "storeid=" + storeid + "&roomNo=" + roomNo + "&orderTypeCode=" + orderTypeCode + "&duration=" + duration + "&integral=" + integral + "&fenpeiType=" + fenpeiType;
	//分配方式不同，参数不同
	if(fenpeiType == "1") {
		for(var index = 0 ; selectedFenpeis != null && index < selectedFenpeis.length ; index++) {
			var selectedFenpei = selectedFenpeis[index];
			data += "&usergroupid=" + $(selectedFenpei).val();
		}
	}
	if(fenpeiType == "2") {
		data += "&zhipaiUserid=" + zhipaiUserid;
	}
	
	//抢单模式不同，参数不同
	if(orderTypeCode == "0001") {
		for(var index = 0 ; selectedCommodityTrs != null && index < selectedCommodityTrs.length ; index++) {
			var selectedCommodityTr = $(selectedCommodityTrs[index]);
			var commodityid = selectedCommodityTr.attr("commodityid");
			var commodityNumber = selectedCommodityTr.attr("commodityNumber")
			parrten = /^[\d]+$/;
			if(!parrten.test(commodityNumber)) {
				alert("商品数量只能填写正整数，请检查！");
				return;
			}
			data += "&commodityid=" + commodityid + "&commodityNumber=" + commodityNumber;
		}
	} else {
		data += "&remark=" + encodeURI(remark);
	}
	
	//=====================请求
	$.ajax({
        url: "${prefix}/order/createOrder",
        async: false,
        dataType: "json",
        data: data,
        success: function(data) {
        	if(data.responsecode != "E200") {
				alert(data.errorinfo);
				return;
			}
        	
        	//添加成功后，清空所有信息。光标指向“房间号”；以便进行下一次添加
        	$("#roomNo").val("");
        	$("#orderType").val("");
        	$("#orderTypeName").html("");
        	$("#ordertypeDetails").css("display","none");
        	$("#duration").val("");
        	$("#integral").val("");
        	//分配方式默认指向“1”
        	$("#fenpeiType").val("");
        	$("#qiangdanModuleDiv").css("display","none");
        	$("#zhipaiModuleDiv").css("display","none");
        	$("#commodityDetailsDiv").css("display","none");
        	//清空“指派模式”
        	$("#zhipaiModule_userCode").val("");
        	$("#zhipaiModule_userid").val("");
        	$("#zhipaiModule_userName_view").html("");
        	
        	//重构可能的商品区域
        	var html = "<tr>";
        	html += "<td>";
        	html += "<input type=\"text\" id=\"commoditySelectText\" style=\"margin-right: 10px\"/>[请输入商品关键字]";
        	html += "<input type=\"hidden\" id=\"commoditySelectText_uid_hidden\">";
        	html += "<input type=\"hidden\" id=\"commoditySelectText_name_hidden\">";
        	html += "<input type=\"hidden\" id=\"commoditySelectText_sortname_hidden\">";
        	html += "</td>";
        	html += "<td>";
        	html += "<input type=\"text\" id=\"commodityNumberText\">";
        	html += "</td>";
        	html += "<td>&nbsp;</td>";
        	html += "</tr>";
        	$("#commodityDetailsTbody").html(html);
        	
        	$("#remarkDetailsDiv").css("display","none");
        	$("#remark").val("");
        	
        	//提示创建成功
        	$("#roomNo").focus();
        	alert("工单创建成功！");
        }
    });
}
</script>

<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
	<script src="${prefix}/javascripts/html5.js"></script>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="${prefix}/lib/font-awesome/docs/assets/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" href="${prefix}/lib/font-awesome/docs/assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="${prefix}/lib/font-awesome/docs//assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="${prefix}/lib/font-awesome/docs//assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="${prefix}/lib/font-awesome/docs//assets/ico/apple-touch-icon-57-precomposed.png">
</head>

<!--[if lt IE 9]>
<style>
.reveal-modal-bg{filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#cc000000,endColorstr=#cc000000);}
</style>
<![endif]-->

<!--[if lt IE 7 ]> <body class="ie ie6"> <![endif]-->
<!--[if IE 7 ]> <body class="ie ie7"> <![endif]-->
<!--[if IE 8 ]> <body class="ie ie8"> <![endif]-->
<!--[if IE 9 ]> <body class="ie ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> 
<body>
<!--<![endif]-->
<div class="navbar">
	<%@ include file="/commonjsp/userbar.jsp"%>
</div>

<div class="container-fluid">
	<div class="row-fluid">
		<%@ include file="/commonjsp/mainmenu.jsp"%>
		
		<!-- app 资源详情 -->
		<div class="span9">
			<h1 class="page-title">工单创建</h1>
			
			<!-- 操作按钮 -->
			<div class="btn-toolbar">
				<a href="javascript:void(0);" id="savebutton" onclick="saveOrdertype()" class="btn btn-primary"><i class="icon-save"></i> Save</a>
			</div>
			
			<div class="well">
				<div id="myTabContent" class="tab-content">
					<!-- 公司基本信息 -->
					<div class="tab-pane active in" id="home" >
						<label>基本信息：${company.companyName }公司，${store.storeName }店面，工单创建</label>
						<label>房间号：
							<input type="text" id="roomNo" name="roomNo" class="input-xlarge" maxlength="8" style="width: 100px ; margin-right: 10px" />
						</label>
						<label>工单类型（请输入类型编号）：
							<input type="text" id="orderType" name="orderType" class="input-xlarge" maxlength="16" style="width: 100px ; margin-right: 10px" />
							<font id="orderTypeName"></font>
						</label>
						
						<!-- 工单基本信息——根据工单类型决定 -->
						<div id="ordertypeDetails" style="display:none">
						<label>标准服务时间(秒)：
						<input type="text" value="" id="duration" name="duration" class="input-xlarge" maxlength="4" style="width: 100px" />
						</label>
						<label>工单积分：
						<input type="text" value="" id="integral" name="integral" class="input-xlarge" maxlength="4" style="width: 100px" />
						</label>
						<hr style="color: #FF0000 ; margin: 10px"/>
						<label>
						工单分配方式：
						<select id="fenpeiType" style="width: 180px ; height: 30px">
							<option value="1">抢单模式</option>
							<option value="2">指派模式</option>
						</select>
						</label>
						</div>
						
						<!-- 抢单模式 -->
						<div id="qiangdanModuleDiv" style="display:none">
							<label>
							分配到：
							<c:forEach items="${userGroups }" var="userGroup">
							<input type="checkbox" name="fenpei" value="${userGroup.uid }" groupType="${userGroup.groupType }" style="margin-right: 5px"/><font style="margin-right: 20px">${userGroup.groupName }</font>
							</c:forEach>
							</label>
						</div>
						<!-- 分配模式 -->
						<div id="zhipaiModuleDiv" style="display: none;">
							<label>请输入员工工号：
							<input type="text" id="zhipaiModule_userCode" value="" class="input-xlarge" maxlength="10" style="width: 100px ;margin-right: 10px" />
							<input type="hidden" id="zhipaiModule_userid"/>
							<font id="zhipaiModule_userName_view"></font> 
							</label>
						</div>
						
						<!-- 商品信息 -->
						<div id="commodityDetailsDiv" style="display:none">
							<table class="table">
								<thead>
								<tr>
									<th>商品名称</th>
									<th>商品数量</th>
									<th style="width:60px">操  作</th>
								</tr>
								</thead>
								<tbody id="commodityDetailsTbody">
								<tr>
									<td>
									<input type="text" id="commoditySelectText" style="margin-right: 10px"/>[请输入商品关键字]
									<input type="hidden" id="commoditySelectText_uid_hidden">
									<input type="hidden" id="commoditySelectText_name_hidden">
									<input type="hidden" id="commoditySelectText_sortname_hidden">
									</td>
									<td>
									<input type="text" id="commodityNumberText">
									</td>
									<td>&nbsp;</td>
								</tr>
								</tbody>
							</table>
						</div>
						
						<!-- 任务说明 -->
						<div id="remarkDetailsDiv" style="display:none">
						<label>任务说明：</label>
						<textarea rows="5" style="width: 360px;height: 140px" id="remark" name="remark"></textarea>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	
    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="${prefix}/lib/bootstrap/js/bootstrap.js"></script>
</div>
</body>
</html>